<template>
    <div class="map-container">
        <el-row :gutter="20">
            <el-col :span="6">
                <div class="search-panel">
                    <el-input
                            v-model="searchQuery"
                            placeholder="请输入地点名称"
                            @keyup.enter="handleSearch"
                    >
                        <template #append>
                            <el-button @click="handleSearch">
                                <el-icon><Search /></el-icon>
                            </el-button>
                        </template>
                    </el-input>

                    <el-divider />

                    <div class="search-results">
                        <el-scrollbar height="400px">
                            <div
                                    v-for="(item, index) in searchResults"
                                    :key="index"
                                    class="result-item"
                                    @click="handleResultClick(item)"
                            >
                                <div class="result-name">{{ item.title }}</div>
                                <div class="result-address">{{ item.position }}</div>
                            </div>
                        </el-scrollbar>
                    </div>
                </div>
            </el-col>

            <el-col :span="18">
                <div id="map-container" ref="mapContainer"></div>
                <div class="location-info">
                    <el-descriptions :column="2" border>
                        <el-descriptions-item label="省市">{{ locationInfo.province || '--' }}</el-descriptions-item>
                        <el-descriptions-item label="地级市">{{ locationInfo.city || '--' }}</el-descriptions-item>
                        <el-descriptions-item label="区县">{{ locationInfo.district || '--' }}</el-descriptions-item>
                        <el-descriptions-item label="具体地址">{{ locationInfo.position || '--' }}</el-descriptions-item>
<!--                        <el-descriptions-item label="经度">{{ locationInfo.lng || '&#45;&#45;' }}</el-descriptions-item>-->
<!--                        <el-descriptions-item label="纬度">{{ locationInfo.lat || '&#45;&#45;' }}</el-descriptions-item>-->
                    </el-descriptions>
                </div>
            </el-col>
        </el-row>

    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 百度地图API密钥
const BAIDU_MAP_KEY = 'bkLGOc9Vp1oXc79AMJq9aWoobQ2dlYdW'

// 地图实例
let map = null
let localSearch = null
let marker = null

// 数据

const emit = defineEmits(['locationGet'])



const handleLocationGet = () => {
    emit('locationGet', locationInfo.value)
}

const props = defineProps(['id'])


const searchQuery = ref('')
const searchResults = ref([])
const locationInfo = ref({
    province: '',
    city: '',
    district: '',
    position: '',
    lng: '',
    lat: ''
})
const mapContainer = ref(null)

// 初始化地图
const initMap = () => {
    // 动态加载百度地图API
    const script = document.createElement('script')
    script.src = `https://api.map.baidu.com/api?v=3.0&ak=${BAIDU_MAP_KEY}&callback=initBaiduMap`
    script.async = true
    document.head.appendChild(script)

    // 全局回调函数
    window.initBaiduMap = () => {
        // 创建地图实例
        map = new BMap.Map(mapContainer.value)



        // 启用滚轮缩放和平移
        map.enableScrollWheelZoom()
        map.enableDragging()

        // 添加地图点击事件
        map.addEventListener('click', (e) => {
            handleMapClick(e)
        })


        if (props.id) {
            // 设置中心点和缩放级别（根据传入的经纬度）

            // 添加默认标记

            // 创建地理编码服务对象，用于获取地址信息
            const geoc = new BMap.Geocoder()


            // 获取位置的地址信息
            geoc.getLocation(point, async (result) => {
                if (result) {
                    const components = result.addressComponents
                    locationInfo.value = {
                        province: components.province || '',
                        city: components.city || components.province || '', // 处理直辖市
                        district: components.district || '',
                        position: result.address || '',
                        lng: point.lng.toFixed(6),
                        lat: point.lat.toFixed(6)
                    }

                }
            })
        }else {
            // 设置默认中心点和缩放级别（北京）
            const point = new BMap.Point(116.404, 39.915)
            map.centerAndZoom(point, 9)
        }


        // 初始化本地搜索
        localSearch = new BMap.LocalSearch(map, {
            renderOptions: { map: map, panel: null },
            onSearchComplete: (results) => {
                if (localSearch.getStatus() !== BMAP_STATUS_SUCCESS) {
                    ElMessage.error('搜索失败，请重试')
                    return
                }

                searchResults.value = []
                for (let i = 0; i < results.getNumPois(); i++) {
                    const poi = results.getPoi(i)
                    searchResults.value.push({
                        title: poi.title,
                        position: poi.address,
                        point: poi.point
                    })
                }
            }
        })
    }
}

// 处理搜索
const handleSearch = () => {
    if (!searchQuery.value.trim()) {
        ElMessage.warning('请输入搜索关键词')
        return
    }

    localSearch.search(searchQuery.value)
}

// 处理搜索结果点击
const handleResultClick = (item) => {
    // 清除之前的标记
    if (marker) {
        map.removeOverlay(marker)
    }

    // 添加新标记
    marker = new BMap.Marker(item.point)
    map.addOverlay(marker)

    // 设置地图中心点
    map.panTo(item.point)

    // 获取详细地址信息
    getLocationDetails(item.point)
}

// 处理地图点击
const handleMapClick = (e) => {
    // 清除之前的标记
    if (marker) {
        map.removeOverlay(marker)
    }

    // 添加新标记
    marker = new BMap.Marker(e.point)
    map.addOverlay(marker)

    // 获取详细地址信息
    getLocationDetails(e.point)
}

// 获取位置详细信息
const getLocationDetails = (point) => {
    const geoc = new BMap.Geocoder()
    geoc.getLocation(point, (result) => {
        if (result) {
            const components = result.addressComponents

            locationInfo.value = {
                province: components.province || '',
                city: components.city || components.province || '', // 处理直辖市
                district: components.district || '',
                position: result.address || '',
                lng: point.lng.toFixed(6),
                lat: point.lat.toFixed(6)
            }
            handleLocationGet()
        }
    })
}

// 生命周期钩子
onMounted(() => {
    initMap()
})

onBeforeUnmount(() => {
    // 清理
    if (window.BMap) {
        delete window.initBaiduMap
    }
})
</script>

<style scoped>
.submit-map {
    text-align: center;
    margin-top: 20px;
}
.map-container {
    width: 100%;
    height: 620px;
}

#map-container {
    width: 100%;
    height: 500px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 10px;
}

.search-panel {
    padding: 10px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    height: 620px;
}

.search-results {
    margin-top: 10px;
}

.result-item {
    padding: 10px;
    border-bottom: 1px solid #eee;
    cursor: pointer;
}

.result-item:hover {
    background-color: #f5f7fa;
}

.result-name {
    font-weight: bold;
    margin-bottom: 5px;
}

.result-address {
    color: #999;
    font-size: 12px;
}

.location-info {
    background: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-descriptions__body) {
    background: #fafafa;
}
</style>